<template>
  <div class="container">
    <div class="content">
      <div class="content-inner">
        <div class="login-form-wrapper">
          <div class="login-form-title" style="width: 600px;">GinMeta-Admin</div>
        </div>
        <el-form class="login-form" layout="vertical" ref="loginForm" :model="userInfo">
          <el-form-item prop="username" :trigger="['change', 'blur']" hide-label
                        :rules="[{ required: true, message: '用户名不能为空' }]">
            <el-input v-model="userInfo.username" placeholder="请输入用户名">
              <template #prefix>
                <el-icon>
                  <User/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password" :trigger="['change', 'blur']" hide-label
                        :rules="[{ required: true, message: '密码不能为空' }]">
            <el-input v-model="userInfo.password" type="password" placeholder="请输入密码" allow-clear>
              <template #prefix>
                <el-icon>
                  <Lock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-space :size="16" direction="vertical" style="width: 100%;">
            <el-button type="primary" :loading="loading" @click="handleSubmit">
              登录
            </el-button>
            <el-button type="default" class="login-form-register-btn" @click="registerBut">
              注册
            </el-button>
          </el-space>
        </el-form>
      </div>
      <div class="footer">
        <Footer/>
      </div>
    </div>

    <!--  注册表单弹窗  -->
    <el-dialog ref="modalRef" v-model:visible="formModelSetting.visible" :ok-loading="formModelSetting.onLoading"
               :mask-closable="false" :title="formModelSetting.title" title-align="start"
               :ok-text="formModelSetting.okTest" @cancel="modelCancelBut" @before-ok="modelBeforeOkBut"
               @ok="modelOkBut">
      <el-form ref="formRef" :model="formData" auto-label-width>
        <el-form-item prop="username" label="用户名" :rules="[{required:true,message:'请输入用户名'}]">
          <el-input v-model="formData.username" :max-length="20" show-word-limit placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item prop="password" label="密码" :rules="[{required:true,message:'请输入密码'}]">
          <el-input v-model="formData.password" :max-length="18" placeholder="请输入密码" type="password"/>
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码" :rules="[{required:true,message:'请输入密码'}]">
          <el-input v-model="formData.confirmPassword" :max-length="18" placeholder="请输入密码" type="password"/>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import Footer from '@/components/footer/index.vue';
import {reactive, ref} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage, ElNotification} from 'element-plus';
import {useUserStore} from '@/store';
import {register, RegisterData} from '@/api/login/login';
import useLoading from '@/hooks/loading';
import {encrypt} from '@/utils/jsencrypt';

// 遮罩
const {loading, setLoading} = useLoading();
// 用户store
const userStore = useUserStore();
// 路由
const router = useRouter();
const loginForm = ref();
// 登陆参数
const userInfo = reactive({
  username: '',
  password: ''
});
// 表单提交
const handleSubmit = async () => {
  if (loading.value) return;
  loginForm.value.validate(async (valid: any) => {
    console.log(valid)
    if (valid) {
      setLoading(true);
      try {
        const params = JSON.parse(JSON.stringify(userInfo));
        params.password = encrypt(params.password);
        params.types = ['admin'];
        await userStore.login(params);
        const {redirect, ...othersQuery} = router.currentRoute.value.query;
        await router.push({
          name: (redirect as string) || 'Home',
          query: {
            ...othersQuery,
          },
        });
        ElNotification.success({
          message: '登录成功',
          duration: 1000
        });
      } catch (err) {

      } finally {
        setLoading(false);
      }
    }
  })
};

// 对话框是否展示
const formModelSetting = reactive({
  visible: false,
  onLoading: false,
  title: "注册账号",
  okTest: "注册",
});

// 表单模型
const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
});
const modalRef = ref();

// 重置表单模型
const resetFormData = () => {
  formData.username = '';
  formData.password = '';
  formData.confirmPassword = '';
};
const formRef = ref();

// 注册
const registerBut = () => {
  // 重置
  resetFormData();
  // 打开弹窗
  formModelSetting.visible = true;
  formModelSetting.onLoading = false;
}

// 取消按钮
const modelCancelBut = () => {
  // 关闭弹窗
  formModelSetting.visible = false;
  formModelSetting.onLoading = false;
  // 重置表单
  resetFormData();
};

// 表单确定创建之前执行
const modelBeforeOkBut = async () => {
  let flag = true;
  // 提交表单
  await formRef.value.validate().then((res: any) => {
    if (res !== undefined) {
      flag = false;
      formModelSetting.visible = true;
      formModelSetting.onLoading = false;
    }
  });
  // 密码校验
  if (formData.password !== formData.confirmPassword) {
    flag = false;
    ElMessage.warning({
      message: `两次密码输入不一致`,
      duration: 2 * 1000,
    });
  }
  // 注册
  const params: RegisterData = formData;
  const {code, msg}: any = await register(params);
  if (code === 200) {
    ElMessage.success({
      message: `注册成功`,
      duration: 2 * 1000,
    });
    // 关闭弹窗
    flag = true;
  } else {
    // 不关闭弹窗
    flag = false;
    ElMessage.success({
      message: msg,
      duration: 2 * 1000,
    });
  }
  return flag;
};

// 表单确定按钮
const modelOkBut = async () => {
  formModelSetting.visible = false;
  formModelSetting.onLoading = false;
  // 重置表单
  resetFormData();
};
</script>

<style lang="less" scoped>
.container {
  display: flex;
  height: 100vh;
  /*毛玻璃*/
  //background-image: url("@/assets/images/login-background.png");
  //background-size: 100% 100%;

  .content {
    position: relative;
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    padding-bottom: 40px;
    /*毛玻璃*/
    //backdrop-filter: blur(20px);

    /*&-inner {
      position: relative;
      top: 0;
      right: -350px;
    }*/
  }

  .footer {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 100%;
  }
}

.logo {
  position: fixed;
  top: 24px;
  left: 22px;
  z-index: 1;
  display: inline-flex;
  align-items: center;

  &-text {
    margin-right: 4px;
    margin-left: 4px;
    color: var(--color-fill-1);
    font-size: 20px;
  }
}

.login-form {
  &-wrapper {
    width: 320px;
    margin-bottom: 15px;
  }

  &-title {
    color: var(--color-text-1);
    font-weight: 500;
    font-size: 24px;
    line-height: 32px;
  }

  &-sub-title {
    color: var(--color-text-3);
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }
}

:deep(.el-space__item) {
  width: 100%;
}
</style>
